package com.feicheng.common.sms;


import com.feicheng.common.util.StringGenerator;
import com.feicheng.persistence.entity.Amsg;
import com.feicheng.persistence.service.IAmsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedList;

@Component
public class MSGContant extends HashMap<String, MSG> {

    @Autowired
    IAmsgService msgService;

    public Amsg getMsg(String toid, String fromid) {
        if (!this.containsKey(toid)) {
            return null;
        }

        MSG to = this.get(toid);

        Amsg amsg = null;
        synchronized (fromid.intern()) {
            if (!to.containsKey(fromid)) {
                return null;
            }

            LinkedList<Amsg> fromQueue = to.get(fromid);

            if (fromQueue.size() == 0) {
                return null;
            }
            amsg = fromQueue.removeLast();
        }

        amsg.setReadflg(true);
        msgService.updateById(amsg);
        return amsg;
    }

    public Amsg pushMsg(Amsg amsg) {
        amsg.setMsgid(StringGenerator.getID("MSG"));
        amsg.setCt(LocalDateTime.now());
        amsg.setReadflg(false);
        msgService.save(amsg);

        if (!this.containsKey(amsg.getToid())) {
            this.put(amsg.getToid(), new MSG());
        }

        MSG to = this.get(amsg.getToid());

        synchronized (amsg.getFromid().intern()) {
            if (!to.containsKey(amsg.getFromid())) {
                to.put(amsg.getFromid(), new LinkedList<Amsg>());
            }

            LinkedList<Amsg> fromQueue = to.get(amsg.getFromid());
            fromQueue.addFirst(amsg);
        }
        return amsg;
    }


    public void clearMsg(String toid, String fromid) {
        if (!this.containsKey(toid)) {
            return;
        }

        MSG to = this.get(toid);

        Amsg amsg = null;
        synchronized (fromid.intern()) {
            if (!to.containsKey(fromid)) {
                return;
            }

            LinkedList<Amsg> fromQueue = to.get(fromid);

            if (fromQueue.size() == 0) {
                return;
            }
            fromQueue.clear();
        }
    }
}
